package com.lxr0860.lxr0860production_test.itemactivity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.CameraManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.lxr0860.lxr0860production_test.R;
import com.lxr0860.lxr0860production_test.utils.Contants;
import com.lxr0860.lxr0860production_test.view.CustomDialog;

import org.jetbrains.annotations.Nullable;

public class FlashActivity extends Activity implements View.OnClickListener {

    private ImageView iv_flash_drawable;
    private Button btn_flash_switch;
    private CustomDialog.Builder builder;
    private int testType;

    private CameraManager mCameraManager;
    private boolean mTorchAvailable;
    private String mCameraId;
    private boolean mFlashlightEnabled;
    private int flashLightPowerstatus;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_flash);
        iv_flash_drawable = findViewById(R.id.iv_flash_drawable);
        btn_flash_switch = findViewById(R.id.btn_flash_switch);
        btn_flash_switch.setOnClickListener(this);
        testType = getIntent().getIntExtra("testType", Contants.TEST_ZUZHUANG);

        mCameraManager = (CameraManager) this.getSystemService(Context.CAMERA_SERVICE);
        try {
            mCameraId = getCameraId();
        } catch (Throwable e) {
            Log.e("camera", "Couldn't initialize.", e);
            return;
        }
        // 注册针对闪光灯的状态回调
        if (mCameraId != null) {
            mCameraManager.registerTorchCallback(mTorchCallback, null);
        }

        if (!hasFlashlight()) {
            Toast.makeText(this, "不支持闪光灯", Toast.LENGTH_SHORT).show();
         return;
        }
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case Contants.DIALOG_POSITIVE:
                    Intent mIntent = new Intent();
                    Bundle bundle = new Bundle();
                    bundle.putBoolean("result", true);
                    mIntent.putExtras(bundle);
                    FlashActivity.this.setResult(Contants.TEST_ITEM_FLASH, mIntent);
                    finish();
                    break;
                case Contants.DIALOG_NEGATIVE:
                    if (testType == Contants.TEST_QIANGHUA) {
                        builder = null;
                    } else {
                        finish();
                    }
                    break;
            }
        }
    };



    //闪光灯测试
    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btn_flash_switch) {

            if (flashLightPowerstatus == 0) {
                flashLightPowerstatus = 1;
                iv_flash_drawable.setBackgroundResource(R.drawable.flash_on);
                setFlashlight(true);

            }else{
                flashLightPowerstatus = 0;
                iv_flash_drawable.setBackgroundResource(R.drawable.flash_off);
                setFlashlight(false);
                if (builder == null) {
                    builder = Contants.showDailog(FlashActivity.this, "是否保存此次测试结果", handler, Gravity.TOP);
                }
            }
//            flashOpenCloseLight();

        }
    }

    // 判断是否支持
    public boolean hasFlashlight() {
        return this.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
    }



    private String getCameraId() throws CameraAccessException {
        String[] ids = mCameraManager.getCameraIdList();
        for (String id : ids) {
            CameraCharacteristics c = mCameraManager.getCameraCharacteristics(id);
            Boolean flashAvailable = c.get(CameraCharacteristics.FLASH_INFO_AVAILABLE);
            Integer lensFacing = c.get(CameraCharacteristics.LENS_FACING);
            if (flashAvailable != null && flashAvailable
                    && lensFacing != null && lensFacing == CameraCharacteristics.LENS_FACING_BACK) {
                return id;
            }
        }
        return null;
    }

    // 状态回调
    private final CameraManager.TorchCallback mTorchCallback =
            new CameraManager.TorchCallback() {

                @Override
                public void onTorchModeUnavailable(String cameraId) {
                    if (TextUtils.equals(cameraId, mCameraId)) {
                        setCameraAvailable(false);
                    }
                }

                @Override
                public void onTorchModeChanged(String cameraId, boolean enabled) {
                    if (TextUtils.equals(cameraId, mCameraId)) {
                        setCameraAvailable(true);
                        mFlashlightEnabled = enabled;
                    }
                }

                private void setCameraAvailable(boolean available) {
                    mTorchAvailable = available;
                }
            };

    // 开启/关闭闪光灯
    public void setFlashlight(boolean enabled) {
        synchronized (this) {
            if (mCameraId == null || !mTorchAvailable){
                return;
            }
            if (mFlashlightEnabled != enabled) {
                mFlashlightEnabled = enabled;
                try {
                    mCameraManager.setTorchMode(mCameraId, enabled);
                } catch (CameraAccessException e) {
                    Log.e("camera", "Couldn't set torch mode", e);
                }
            }
        }
    }
}

